<template>
  <div>
    购物车
    <div>
      全选 <input @change="allSelectChange"
                  v-model="allSelect"
                  type="checkbox"/>
    </div>

    <div>
      <div v-for="(item,index) in goods" :key="index">
        <input v-model="item.select" @change="singleSelect" type="checkbox">
        商品名： {{ item.name }} ---
        价格：--- {{ item.price }}
        <button @click="updateNum(1,index)"> + </button>
        {{ item.num || 1 }}
        <button @click="updateNum(-1,index)"> - </button>
        小计：{{ item.price * (item.num || 1) }}
      </div>
    </div>
    总计：
    {{
      goods.filter(item => item.select)
          .reduce((total, item) => (total + (item.num || 1) * item.price), 0)
    }}
  </div>
</template>

<script>

export default {
  data() {
    return {
      allSelect: false,
      goods: [
        {name: '猪肉串', price: 10},
        {name: '羊肉串', price: 15},
        {name: '鸡肉串', price: 13},
      ]
    }
  },

  methods: {
    singleSelect() {
      this.allSelect = this.goods.every(item => item.select)
    },
    allSelectChange() {
      this.goods.forEach(it => it.select = this.allSelect)
    },
    updateNum(num, index) {
      this.goods[index].num = this.goods[index].num || 1
      this.goods[index].num += num
    }
  }
}

</script>
